<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { type FormInstance, type FormRules } from "element-plus"
import { updateUserDataApiOne, updateUserDataApi, getmapApi } from "@/api/user"
import { ElMessage, ElTree } from "element-plus"
import { useUserStore } from "@/store/modules/user"
import { usePagination } from "@/hooks/usePagination"
import { checkPw } from "@/utils/validate"

interface Tree {
  [key: string]: any
}
const activeName = ref("one")
const { paginationData } = usePagination()

//  #region  修改昵称和修改密码
const userStore = useUserStore()
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  password: "",
  newpassword: "",
  nickName: ""
})

const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value !== ruleForm.password) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  password: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { validator: checkPw, trigger: "blur" }
  ],
  newpassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" }
  ],
  nickName: [{ required: true, message: "请输入新昵称", trigger: "blur" }]
})
// 用户修改密码
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid: any) => {
    if (valid) {
      updateUserDataApiOne({
        department: userStore.department,
        id: userStore.usernameID,
        name: userStore.username,
        nickName: userStore.nickName,
        password: ruleForm.password,
        team: userStore.teamName,
        role: userStore.userrole,
        maxOrder: userStore.usermaxOrder
      }).then(() => {
        ElMessage.success("修改成功")
        userStore.resetToken()
        userStore.logout()
      })
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  ruleForm.nickName = ""
}
// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const edit = () => {
  clearValidate()
  ruleForm.nickName = ""
}
// 修改昵称
const formRef = ref<FormInstance | null>(null)
const submitNick = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      updateUserDataApi({
        id: userStore.usernameID,
        name: userStore.username,
        password: userStore.password,
        team: userStore.teamName,
        role: userStore.userrole,
        nickName: ruleForm.nickName,
        department: userStore.department,
        maxOrder: userStore.usermaxOrder
      }).then(() => {
        ElMessage.success("修改成功")
        ruleForm.nickName = ""
        window.location.reload() // 刷新页面
      })
    } else {
      return false
    }
  })
}
console.log(userStore.userMoney, "123123---")
// #endregion

const loading = ref(true)
const sourceData = ref([])
const defaultProps = {
  children: "lowerLevel",
  label: "name"
}
const treeRef = ref<InstanceType<typeof ElTree>>()
const filterText = ref("")
const data = ref<any>(sourceData)
const getTableData = () => {
  getmapApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    team: userStore.teamName
  }).then((res: any) => {
    sourceData.value = res.data
    loading.value = false
    console.log(res.data, "123456")
  })
}
getTableData()

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
</script>

<template>
  <div class="app-container">
    <el-card>
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="账户余额" name="one"> {{ userStore.userMoney }} </el-tab-pane>
        <el-tab-pane label="修改昵称" name="two">
          <el-form ref="formRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
            <el-form-item label="新昵称" prop="nickName">
              <el-input v-model="ruleForm.nickName" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitNick"> 确定 </el-button>
              <el-button @click="edit">清空</el-button>
            </el-form-item>
          </el-form></el-tab-pane
        >
        <el-tab-pane label="修改密码" name="stree">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
            status-icon
          >
            <el-form-item label="新密码" prop="password">
              <el-input v-model="ruleForm.password" show-password maxlength="16" />
            </el-form-item>
            <el-form-item label="确认密码" prop="newpassword">
              <el-input v-model="ruleForm.newpassword" show-password />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
              <el-button @click="resetForm(ruleFormRef)">清空</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="地址查询" name="four" v-loading="loading" element-loading-text="加载中...">
          <el-form-item label="查询全国地址" prop="nickName">
            <el-input v-model="filterText" placeholder="查询地址" />
          </el-form-item>

          <el-tree
            ref="treeRef"
            class="filter-tree"
            :default-expand-all="false"
            :data="data"
            :props="defaultProps"
            :filter-node-method="filterNode" />
          <el-divider
        /></el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
